<template>
  <!--添加印章-->
  <view class="agree_jn">
    <uni-forms ref="form" :modelValue="form" :rules="rules" label-position="top">
      <!--基本信息-->
      <view class="form-title">基本信息</view>
      <uni-forms-item label="印章名称" name="name" required>
        <uni-easyinput placeholder="请输入印章名称" type="text" maxlength="50" v-model="form.name"/>
      </uni-forms-item>
      <uni-forms-item label="印章类型" name="sealTypeId" required>
        <uni-data-select placeholder="请选择印章类型" v-model="form.sealTypeId" :localdata="sealTypeList"
                         :clear="false"/>
      </uni-forms-item>
      <!--制章方式-->
      <view class="form-title">印章制作</view>
      <uni-data-checkbox mode="button" v-model="makeType" :localdata="makeTypes"/>
      <!--上传章面图-->
      <div v-if="makeType == 0">
        <seal-add-cropper @success="setLocalSealImgData"/>
      </div>
      <!--印章模板库-->
      <div v-else>
        <seal-add-generate @success="setGenerateSealImgData"/>
      </div>
    </uni-forms>
    <view class="submit_btn">
      <button size="mini" class="back-Btn" @click="cancel">取消</button>
      <button size="mini" class="next-Btn" @click="submitForm">
        {{ (makeType == 0) ? '提交审核' : '完成制作' }}
      </button>
    </view>
    <!--该行代码的作用就是：使用sealFont字体时候防止第一次使用字体无法生效-->
    <view style="font-family: sealFont;visibility: hidden;font-size: 0px;">0</view>
  </view>
</template>

<script>
import config from '@/config'
import {getToken} from '@/utils/auth'
import sealAddCropper from "./sealAddCropper";
import sealAddGenerate from "./sealAddGenerate";
import {listByCompanyId} from "@/api/ec/console/seal/sealType";
import {addSealCompanyForGenerate} from "@/api/ec/console/seal/sealCompany";

export default {
  components: {sealAddCropper, sealAddGenerate},
  data() {
    return {
      // url地址
      host: config.baseUrl,
      // 印章类型
      sealTypeList: [],
      // 制章方式 0：印章模板库，1：上传章面图
      makeType: 0,
      // 制章方式
      makeTypes: [{text: '上传章面图', value: 0}, {text: '印章模板库', value: 1}],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: {rules: [{required: true, errorMessage: '印章名称不能为空'}]},
        sealTypeId: {rules: [{required: true, errorMessage: '请选择印章类型'}]},
      },
      // 选中的印章规格
      selectSealSpec: null,
      // 本地上传印章图片
      localSealImgBase64: null,
      // 印章Base64图片字符
      sealGenerateBase64: null,
      // 印章横排文字
      sealHorizontalText: null,
      // 印章英文文字
      sealEnglishName: null,
    }
  },
  created() {
    this.getSealType();
  },
  methods: {
    /** 取消 */
    cancel() {
      uni.navigateBack({delta: 1})
    },
    /** 查询印章类型列表 */
    getSealType() {
      listByCompanyId().then(response => {
        let list = response.data
        let range = [];
        list.forEach((item, index) => {
          range.push({value: parseInt(item.id), text: item.name})
        });
        this.sealTypeList = range;
      });
    },
    /** 印章本地上传图片剪切完成回调 */
    setLocalSealImgData(specData, sealBase64) {
      this.selectSealSpec = specData;
      this.localSealImgBase64 = sealBase64;
    },
    /** 印章图片制作完成回调 */
    setGenerateSealImgData(specData, sealBase64, horizontalText, englishName) {
      this.selectSealSpec = specData;
      this.sealGenerateBase64 = sealBase64;
      this.sealHorizontalText = horizontalText;
      this.sealEnglishName = englishName;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate().then(valid => {
        if (valid) {
          if (this.makeType == 0) {
            // 本地印章图片上传添加
            this.addLocalSealCompany();
          } else {
            // 印章制作上传添加
            this.addGenerateSealCompany();
          }
        }
      });
    },
    /** 本地印章图片上传添加 */
    addLocalSealCompany() {
      if (this.selectSealSpec == null) {
        this.$modal.msgError('请先选择印章规格!');
        return;
      }
      if (this.localSealImgBase64 == null) {
        this.$modal.msgError("请先上传印章图片!");
        return;
      }
      let arrayBuffer = uni.base64ToArrayBuffer(this.localSealImgBase64.replace(/^data:image\/\w+;base64,/, ""))
      let blob = new Blob([arrayBuffer], {type: "image/png"});
      this.$modal.loading();
      uni.uploadFile({
        url: this.host + "/console/sealCompany/addForLocal",
        file: blob,
        header: {'Authorization': 'Bearer ' + getToken(),},
        name: 'sealFile',
        formData: {'name': this.form.name, 'sealTypeId': this.form.sealTypeId, 'sealSpecId': this.selectSealSpec.id},
        success: (res) => {
          uni.hideLoading();
          let response = JSON.parse(res.data);
          if (response.code == 200) {
            this.$modal.msgSuccess("提交完成!");
            uni.$emit("refreshSealCommon", 1);
            this.cancel();
          } else {
            this.$modal.msgError("提交失败!");
          }
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
    /** 印章制作上传添加 */
    addGenerateSealCompany() {
      if (this.selectSealSpec == null) {
        this.$modal.msgError('请先选择印章规格!');
        return;
      }
      if (this.sealGenerateBase64 == null) {
        this.$modal.msgError("请先制作印章图片!");
        return;
      }
      let formData = {
        sealBase64: this.sealGenerateBase64,
        name: this.form.name,
        sealTypeId: this.form.sealTypeId,
        sealSpecId: this.selectSealSpec.id,
        horizontalText: this.sealHorizontalText,
        englishName: this.sealEnglishName,
      };
      this.$modal.loading();
      addSealCompanyForGenerate(formData).then((response) => {
        uni.hideLoading();
        this.$modal.msgSuccess("提交完成!");
        uni.$emit("refreshSealCommon", 1);
        this.cancel();
      }).catch(() => {
        uni.hideLoading();
        this.$modal.msgError("提交失败!");
      });
    },
  }
}
</script>

<style scoped lang="scss">

page {
  background: $uni-bg-color;
}

::v-deep .uni-forms-item__label {
  height: 50rpx;
}

::v-deep .uni-forms-item {
  margin-bottom: 28rpx;
}

.agree_jn {
  padding: 20rpx;
  position: relative;
}

.form-title {
  font-size: 24rpx;
  font-weight: 500;
  color: #1c1c1c;
  padding-bottom: 20rpx;
}

.form-title:before {
  display: inline-block;
  content: " ";
  width: 6rpx;
  height: 26rpx;
  margin-right: 15rpx;
  background: $uni-color-primary;
  vertical-align: -0.15em;
}

.submit_btn {
  display: flex;
  margin: 100rpx auto 0;
  justify-content: space-between;
  width: 80%;

  button {
    width: 40%;
    font-size: 28rpx;
  }

  .next-Btn {
    background-color: $uni-color-primary;
    border-radius: 10rpx;
    color: #fff;
  }

  .back-Btn {
    border-radius: 10rpx;
    border: solid 1rpx $uni-color-primary;
    color: $uni-color-primary;
    background: #fff;
  }
}

</style>
